<template>
  <div class="portal-layout-wrapper">
    <div class="environent-mark" v-if="env === 'development'">{{envName}}</div>
    <mourning v-if="hasMourningModule"></mourning>
    <q-layout
      view="hhh lpr fff"
      class="portal-layout"
      :class="`locale-${this.$i18n.locale}`"
      @scroll="scrollTop = $event.position;"
    >
      <q-header class="bg-white">
        <div class="my_banner row no-wrap full-width">
          <div class="main-menu row full-height justify-between items-center q-pl-lg no-wrap">
            <div class="row items-center no-wrap">
              <q-img class="logo q-mr-sm" src="images/logo.svg"
                width="50px" height="50px" style="min-width:50px"></q-img>
              <div class="flex column">
                <div class="title text-uppercase ellipsis">{{ $t('人工智能互联互通开源评测平台') }}</div>
                <div class="q_title ellipsis">{{ $t('面向人工智能基础技术及应用的检验检测基础服务平台') }}</div>
              </div>
            </div>
          </div>
          <div class="flex justify-center items-center q-px-md q-pr-lg">
              <div class="flex column my_login">
                <div class="row no-wrap items-center q-mb-xs">
                  <q-btn v-if="userName" dense flat round icon="fas fa-bell"
                    class="q-mr-md"
                    :class="data.notifyCount ? 'text-primary' : 'text-grey'"
                    size="14px"
                    @click="data.notifyCount && $router.push('/uc/notifications')">
                    <q-badge color="red" floating
                      v-if="data.notifyCount">{{data.notifyCount}}</q-badge>
                  </q-btn>
                  <q-btn v-if="userName" dense flat class="user-profile-btn">
                    <span class="user-name ellipsis">
                      <q-avatar size="40px">
                        <img v-if="userAvatar" :src="(userAvatar.id || userAvatar) | serverImage">
                        <img v-else src="images/admin/company@2x.png">
                      </q-avatar>
                    </span>
                    <q-menu content-class="portal-user-profile-menu" @input="ucMenuShown = $event">
                      <q-list style="min-width: 191px">
                        <q-item
                          v-if="hasAdminPermission"
                          class="menu-item uc-btn full-width cursor-pointer"
                          clickable
                          @click="toBackend"
                          v-close-popup>
                          <q-item-section>
                            <div class="menu-item-label">{{$t('后台入口')}}</div>
                          </q-item-section>
                        </q-item>
                        <q-item
                          class="menu-item uc-btn full-width cursor-pointer"
                          clickable
                          @click="$router.push('/uc')"
                          v-close-popup>
                          <q-item-section>
                            <div class="menu-item-label">{{$t('用户中心')}}</div>
                          </q-item-section>
                        </q-item>
                        <q-separator></q-separator>
                        <q-item
                          class="menu-item logout-btn full-width cursor-pointer"
                          clickable
                          @click="logoutClicked"
                          v-close-popup>
                          <q-item-section>
                            <div class="menu-item-label">{{$t('LOGOUT')}}</div>
                          </q-item-section>
                        </q-item>
                      </q-list>
                    </q-menu>
                  </q-btn>

                  <div v-else class="row no-wrap">
                    <div class="btn cursor-pointer" dense flat
                      @click="$router.push('/login')">{{ $t("登录") }}</div>
                    <div class="btn cursor-pointer" dense flat
                      @click="$router.push('/register')">{{ $t("注册") }}</div>
                  </div>
                </div>
              </div>
            </div>
        </div>

        <div class="my_nav row no-wrap justify-center full-height"
          :class="{'multi-line1': $i18n.locale !== 'en-us'}">
          <div class="row items-end relative-position no-wrap">
            <div
              class="main-menu-item cursor-pointer"
              v-for="(menu, idx) in (data.menus || []).filter((mm) => !mm.Parent) || []"
                :key="idx"
              :class="{ active: currentPath === menu.Route
                  || (subMenus.length && hoverMenu === menu._id) }"
            >
              <q-btn
                @mouseenter="mouseEnterMenuItem(menu, idx)"
                size="18px"
                style="color:#6E6E6E"
                flat :to="menu.Route">
                <div class="column items-center justify-center no-wrap">
                  <div class="no-wrap">{{ menu.Label }}</div>
                  <!-- <span class="sub-label"
                    v-if="$i18n.locale !== 'en-us'">
                    {{menu.english || $t(menu.Label, 'en-us')}}</span> -->
                </div>
                <q-menu fit
                  ref="submenu"
                  transition-show="fade"
                  transition-hide="fade"
                  :content-style="`height:${(subMenuLists[menu._id]?.length && subMenus.length)
                      ? '' : '0 !important;'}`"
                  :content-class="`portal-main-menu-sub-menus ${menu._id}
                    ${menu.Description && menu.Description.full ? ' full' : ' nest'}`"
                  @hide="hoverMenu=''">
                  <div
                    :class="{
                      row: menu.Description && menu.Description.full,
                      column: !menu.Description || !menu.Description.full,
                      'q-py-md': !menu.Description || !menu.Description.full,
                    }"
                    class="row no-wrap items-start justify-around">
                    <div
                      v-for="(smenu, idx) in subMenus" :key="idx">
                      <div
                        class="menu-category q-ma-xl"
                        v-if="smenu.children.length">
                        {{smenu.Label}}
                        <div class="menu-category-item cursor-pointer q-mt-md"
                          @click.stop="itemClicked(ssmenu.Route)"
                          v-for="(ssmenu, sidx) in smenu.children" :key="sidx">
                          {{ssmenu.Label}}
                        </div>
                      </div>
                      <q-btn flat v-else
                        :to="smenu.Route"
                        class="menu-category-item cursor-pointer q-px-md q-mt-sm">
                        {{smenu.Label}}
                      </q-btn>
                    </div>
                  </div>
                </q-menu>
              </q-btn>
            </div>
          </div>
        </div>

      </q-header>

      <!-- <web-footer :info="data.contactInfo"></web-footer> -->
      <q-page-container>
        <q-page class="portal-page">
          <router-view class="portal-main-content-wrapper"/>
        </q-page>
<!--
        <div class="links-wrapper full-width">
          <links class="frindly-links"
            background="#122442" color="#6e7787"
            :useMenu="true"></links>
        </div> -->
      </q-page-container>

      <!-- <web-footer></web-footer> -->
      <q-footer class="bg-black">
        <div class="full-width q-pa-md q-py-xl text-center">
          <div class="ri row justify-center items-center q-gutter-x-md">
            <div>人工智能互联互通开源评测平台版权所有</div>
            <div>© 2022-{{(new Date()).getFullYear()}}</div>
            <div class="cursor-pointer" @click="toICP" v-if="ICP">{{ICP || '京ICP备00000000号'}}</div>
            <div class="row items-center cursor-pointer"
              v-if="安备"
              clickable @click="toBeian">
              <q-img src="images/portal/ghs.png"
                class="q-mr-xs"
                style="height: 16px; width: 16px;">
              </q-img>京公网安备{{安备 || '11000000000000'}}号</div>
          </div>
        </div>
      </q-footer>
    </q-layout>
  </div>
</template>

<script>
import mixins from 'eis-admin-mixins';
import { canI } from '@/utils/api.js';
// import { RefreshOnLocaleChange } from '../components/mixins/locale';
// import SelectLocales2 from '../components/SelectLocales2';
// import WebFooter from './footer';
// import Links from '../components/links.vue';

export default {
  name: 'PortalLayout',
  mixins: [mixins.ObjectDataMixin],
  components: {
    // SelectLocales2,
    // WebFooter,
    // Links,
  },
  data() {
    return {
      ucMenuShown: false,
      kw: '',
      scrollTop: 0,
      loggedIn: false,
      hasAdminPermission: false,
      hoverMenu: '',
      subMenus: [],
      subMenuLists: {},
      lastSubMenu: undefined,
      ICP: '',
      安备: '',
    };
  },
  meta: {
    title: '人工智能互联互通开源评测平台',
  },
  computed: {
    env() {
      return process.env.env;
    },
    envName() {
      return this.$t(`env_${process.env.env}`);
    },
    hasMourningModule() {
      return !!this.ctx.modules.mourning;
    },
    showFW() {
      return this.$route.fullPath === '/';
    },
    userName() {
      if (this.ctx.modules.passport
        && this.ctx.modules.passport.store.state.passport.user
        && this.ctx.modules.passport.store.state.passport.user.Name) {
        return this.ctx.modules.passport.store.state.passport.user.Name;
      }

      return undefined;
    },
    userAvatar() {
      if (this.ctx.modules.passport
        && this.ctx.modules.passport.store.state.passport.user
        && this.ctx.modules.passport.store.state.passport.user.Avatar) {
        return this.ctx.modules.passport.store.state.passport.user.Avatar;
      }

      return '';
    },
    currentPath() {
      let { fullPath } = this.$route;
      if (fullPath.startsWith('/')) {
        fullPath = fullPath.substring(1);
      }
      const idx = fullPath.indexOf('/');
      if (idx > 0) {
        fullPath = fullPath.substring(0, idx);
      }

      return `/${fullPath}`;
    },
  },
  watch: {
    userName() {
      // user name changed, normally login or out
      this.checkBackendPermission();
    },
  },
  created() {
    this.checkBackendPermission();

    document.getElementsByTagName('html')[0].style.fontSize = '';

    // footer info
    this.getRequest('portal/footer').then((d) => {
      const data = (d && d.data) || {};

      if (data && data.ICP) {
        this.ICP = data.ICP;
      }

      if (data && data.安备) {
        this.安备 = data.安备;
      }
    });

    document.getElementsByTagName('html')[0].style.fontSize = '';
  },
  mounted() {
    this.loadAccScript();
  },
  methods: {
    afterRefresh() {
      if (this.data && this.data.menus && Array.isArray(this.data.menus)) {
        this.data.menus.forEach((menu) => {
          if (menu.Description && (typeof menu.Description === 'string')) {
            try {
              menu.Description = JSON.parse(menu.Description);
            } catch (_) {
              menu.Description = {};
            }

            menu.english = menu.Description.english;
          }

          if (menu.Parent) {
            this.subMenuLists[menu.Parent] = this.subMenuLists[menu.Parent] || [];
            this.subMenuLists[menu.Parent].push(menu);
          }
        });
      }

      if (this.userName) {
        // get real notification count
        // this.getRequest('/noty/count').then((d) => {
        //   if (d && d.data) {
        //     this.$set(this.data, 'notifyCount', d.data.count || 0);
        //   }
        // });
      }
    },
    checkBackendPermission() {
      this.hasAdminPermission = false;

      if (this.userName && this.ctx.modules.passport) {
        this.ctx.modules.passport.utils.isLogedin().then((l) => {
          if (l) {
            canI('/api/系统后台', true).then((r) => {
              if (r) {
                this.hasAdminPermission = true;
              }
            });
          } else {
            // clear info to store
            this.ctx.modules.passport.store.dispatch('passport/clearLoginStatus');
          }
        });
      }
    },
    loadAccScript() {
      if (!this.ctx.config.enableAccessibility) return;

      const sNode = document.getElementById('acc_script');

      if (sNode) return;

      const s = document.createElement('script');
      s.type = 'text/javascript';
      s.id = 'acc_script';
      // s.src = 'http://api.govwza.cn/cniil/assist.js?sid=9685&amp;pos=left&amp;bar=1';
      document.body.appendChild(s);
    },
    scrollToTop() {
      window.scrollTo(0, 0);
    },
    logoutClicked() {
      const passportMdl = this.getModule('passport');

      if (!passportMdl) return;

      passportMdl
        .utils.logout()
        .then(() => {
          // clear info to store
          this.ctx.modules.passport.store.dispatch('passport/clearLoginStatus');
          this.$router.replace('/');
        });
    },
    search(k) {
      const kw = this.kw || k;
      if (kw) {
        this.Bus.$store.commit('portal/SET_KW', kw);
        this.$router.push('/search');
        this.kw = '';
      }
    },
    toBackend() {
      this.$router.push('/admin');
    },

    itemClicked(t) {
      if (!t) return;

      if (this.$route.fullPath !== `/${t}`) {
        this.$router.push(`/${t}`);
      }
    },
    toICP() {
      window.open('https://beian.miit.gov.cn');
    },
    toBeian() {
      window.open(`http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=${this.安备 || ''}`);
    },
    qrcodeClicked(q) {
      if (!q || !q.url) return;

      window.open(q.url);
    },

    mouseEnterMenuItem(menu, idx) {
      // if (!menu.Description || !menu.Description.full) return;

      // eslint-disable-next-line no-underscore-dangle
      this.subMenus = this.subMenuLists[menu._id] || [];

      if (this.subMenus.length) {
        this.subMenus.forEach((sm) => {
          // eslint-disable-next-line no-underscore-dangle
          sm.children = this.subMenuLists[sm._id] || [];
        });

        if (this.lastSubMenu) this.lastSubMenu.hide();

        if (this.$refs.submenu && this.$refs.submenu[idx]) {
          this.$refs.submenu[idx]?.show();
          this.lastSubMenu = this.$refs.submenu[idx];
        }
      }

      // eslint-disable-next-line no-underscore-dangle
      this.hoverMenu = menu._id;
    },
  },
  beforeDestroy() {
    this.$store.commit('app/SET_CRUMBS', undefined);
  },
};
</script>

<style lang="scss" scoped>
$headerHeight: 50px;

.portal-layout {
  min-width: 1300px;
  position: absolute;

  .frindly-links {
    width: 1300px;
    margin: 0 auto;

    color: #6e7787;
  }
}
.my_banner {
  // background-color: #1f4784 !important;
  height: 90px;
  padding: 0;
  color: #525252;
  font-weight: 500;

  .main-menu {
    flex-grow: 1;
  }

  & .title {
    font-size: 24px;
    line-height: 30x;
    max-width: 600px;
  }

  & .q_title {
    font-size: 16px;
  }

  & .my_login {
    margin-left: 20px;
    color: #6E6E6E;

    .btn {
      font-size: 16px;
      padding: 0 4px;

      &:hover {
        border-radius: 2px;
        background: rgba(255,255,255, 0.2);
      }
    }
  }
}

.my_nav{
  // height: 42px;
  // font-size: 18px;

  &.multi-line {
    height: 63px;
  }

  >div{
    height: 100%;
  }

  .main-menu-item {
    &.active {
      position: relative;
      :deep(.q-btn__content) {
        color: #525252;
      }
      &:after {
        content: '';
        height: 3px;
        width: 50px;
        background-color: $primary;
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
      }
    }

    &:not(:last-child) {
      margin-right: 8px;

      .sub-label {
        font-size: 12px;
        line-height: 16px;
        font-weight: 300;
        opacity: 0.65;
      }
    }
  }
}

.portal-user-profile-menu {
  .menu-item {
    .menu-item-label {
      color: #6E6E6E;
    }
  }
}

.environent-mark {
  position: absolute;
  left: -130px;
  top: -80px;
  height: 100px;
  width: 300px;

  font-size: 12px;
  line-height: 100px;
  text-align: center;
  padding-top: 40px;
  padding-right: 70px;
  background-color: #FF0000DD;
  color: white;
  transform: rotate(315deg);

  z-index: 9999999;
}
</style>

<style lang="scss">
.portal-layout {
  input::-webkit-input-placeholder{
      color:#acacac;
      font-size: 14px;
  }
  input::-moz-placeholder{   /* Mozilla Firefox 19+ */
      color:#acacac;
      font-size: 14px;
  }
  input:-moz-placeholder{    /* Mozilla Firefox 4 to 18 */
      color:#acacac;
      font-size: 14px;
  }
  input:-ms-input-placeholder{  /* Internet Explorer 10-11 */
      color:#acacac;
      font-size: 14px;
  }

  textarea::-webkit-input-placeholder{
      color:#acacac;
      font-size: 14px;
  }
  textarea::-moz-placeholder{   /* Mozilla Firefox 19+ */
      color:#acacac;
      font-size: 14px;
  }
  textarea:-moz-placeholder{    /* Mozilla Firefox 4 to 18 */
      color:#acacac;
      font-size: 14px;
  }
  textarea:-ms-input-placeholder{  /* Internet Explorer 10-11 */
      color:#acacac;
      font-size: 14px;
  }

  .global-search-input {
    width: 142px;
    .q-field__append {
      height: 28px;
      font-size: 18px;
    }
    .q-field__control {
      background: black !important;
      opacity: 0.25;
      height: 28px;

      input {
        color: #dddddd !important;
      }

      input:hover {
        color: #000000;
      }
    }
    .q-field__control:before {
      display: none;
    }
  }
}
</style>

<style lang="scss">
.list-layout-container {
  .list-content {
    .items {
      .no-data-label {
        font-size: 14px;
        min-height: 300px;
        color: #acacac;
        position: relative;
      }
    }
  }
}
</style>

<style lang="scss">
.login-layout {
  .q-field {
    .q-field__control {
      border: 0 !important;
      padding: 0 !important;

      .q-field__prepend {
        padding-right: 0;
        i {
          width: 44px;
          height: 38px;
          background: #F2F2F2;
          color: #afafaf;
          position: relative;
          left: 1px;
          border-top-left-radius: 4px;
          border-bottom-left-radius: 4px;
        }
      }
      .q-field__control-container {
        .q-field__native {
          padding-bottom: 0;
        }
        input,.q-field__label {
          padding-left: 10px;
          padding-top: 0;
        }
        textarea {
          padding-left: 10px !important;
          padding-top: 10px !important;
        }
      }
    }
  }

  .q-field--error {
    .q-field__control:before {
      display: none;
    }
    .q-field__inner {
      border: 1px solid $negative;
    }
    .q-field__prepend {
      i {
        color: $negative !important;
        border-right: 1px solid $negative;
      }
    }
  }
}

.q-breadcrumbs__el, .q-breadcrumbs__separator {
  font-size: 15px;
  color: #666666;
}
</style>

<style lang="scss">
.portal-main-menu-sub-menus {
  &.full {
    min-width: 100vw !important;
    left: 0 !important;
  }

  .menu-category {
    color: $primary;
    font-size: 20px;
    font-weight: 500;

    &-item {
      font-size: 16px;
      color: #575757;
      font-weight: 400;
    }
  }
}
</style>
